package com.qf.auth.service.impl;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.qf.auth.feign.CheckCodeFeign;
import com.qf.auth.service.CheckCodeService;
import com.qf.common.bean.R;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * @author 千锋健哥
 */
@Service
public class CheckCodeServiceImpl implements CheckCodeService {

    //阿里云短信服务子账户key
    @Value("${aliyun.accessKey}")
    private String accessKey;

    //阿里云短信服务子账户秘钥
    @Value("${aliyun.accessSecret}")
    private String accessSecret;

    //阿里云短信模板编码
    @Value("${aliyun.templateId}")
    private String templateId;

    @Autowired
    private CheckCodeFeign checkCodeFeign;

    @Override
    public R<Boolean> send(String phone) throws Exception {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKey)  //your-accessKeyId
                .accessKeySecret(accessSecret)  //your-accessKeySecret
                .build());

        //创建异步请求客户端
        AsyncClient client = AsyncClient.builder()
                .region("cn-wuhan") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create().setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        //设置请求参数
        String code = getCode();
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phone)
                .templateCode(templateId)
                .templateParam("{\"code\":\""+code+"\"}")
                .signName("畅购")
                .build();

        //请求发送短信
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = response.get();
        client.close();
        if("OK".equalsIgnoreCase(resp.getBody().getCode())){
            //短信发送成功后将正确的短信验证码存储到缓存（redis）
            checkCodeFeign.save(phone, code);
            return R.ok();
        }else{
            return R.fail();
        }
    }

    /**
     * 生成随机6位数字验证码
     * @return
     */
    private String getCode(){
        String code = "";
        for (int i = 0; i < 6; i++) {
            code += (int)(Math.random()*10);
        }
        return code;
    }

}
